import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { errorResponse, successResponse, optionsResponse } from '@/lib/response';
import { prisma } from '@/lib/prisma';
import { uploadFile } from '@/lib/storage';
import { authenticateRequest } from '@/utils/auth';
import { randomUUID } from 'crypto';

// create-content 接口
// - 路径: POST /api/system/create-content
// - 说明: 接受 content 实体、agent 实体、分类名称、imageUrl 或 svg 字符串，
//   如提供 imageUrl 则下载上传作为封面；否则将 svg 字符串上传为封面。
//   如果提供了 agent 或 content.type=2（智能体），会优先创建 Agent 再创建内容；
//   分类会按名称在默认菜单（amazing-website）下查找，不存在则创建。
//
// 请求体 JSON 字段:
// {
//   "content": {
//     "title": "必填，内容标题",
//     "content": "可选，正文富文本或纯文本",
//     "summary": "可选，简述",
//     "url": "可选，站点地址/落地页",
//     "type": 1, // 可选：1-网站 2-智能体 3-资讯；若传 agent 则默认 2
//     "isBanner": 0 // 可选：是否 Banner，0/1
//   },
//   "agent": {
//     "name": "可选，智能体名称",
//     "welcomeText": "可选，欢迎语",
//     "prompt": "可选，提示词",
//     "canUploadImg": 0,
//     "canUploadDoc": 0,
//     "isFormEnabled": 0,
//     "formJson": "可选",
//     "secretKey": "可选，不传则使用默认 fastgpt-*"
//   },
//   "categoryName": "必填，分类名称",
//   "imageUrl": "可选，封面图片地址（优先）",
//   "svgString": "可选，SVG 字符串（imageUrl 缺省时作为封面）",
//   "sysCode": "必填，系统代码"  
// }
//
// 响应体:
// {
//   "contentId": "内容ID",
//   "agentId": "智能体ID（若创建）",
//   "categoryId": "分类ID",
//   "cover": { "fileId": "文件ID", "url": "封面URL", "path": "对象Key" }
// }
//
// 示例:
// POST /api/system/create-content
// {
//   "content": {
//     "title": "超好用的翻译工具",
//     "summary": "多语言实时翻译",
//     "url": "https://example.com",
//     "type": 1,
//     "isBanner": 0
//   },
//   "agent": {
//     "name": "翻译助理",
//     "prompt": "你是一位专业翻译官",
//     "canUploadImg": 0,
//     "canUploadDoc": 1
//   },
//   "categoryName": "AI工具",
//   "imageUrl": "https://example.com/cover.jpg",
//   "sysCode": "amazing-website"
// }

function guessExt(contentType: string | null, fileUrl: string): string {
  const fromType = (type: string) => {
    if (type.includes('png')) return 'png';
    if (type.includes('jpeg')) return 'jpg';
    if (type.includes('jpg')) return 'jpg';
    if (type.includes('gif')) return 'gif';
    if (type.includes('webp')) return 'webp';
    if (type.includes('svg')) return 'svg';
    return '';
  };
  const byType = contentType ? fromType(contentType) : '';
  if (byType) return byType;
  try {
    const url = new URL(fileUrl);
    const ext = url.pathname.split('.').pop()?.toLowerCase();
    if (ext) return ext;
  } catch {}
  return 'jpg';
}

async function ensureAmazingWebsiteMenu(sysCode: string) {
  const menu = await prisma.menu.findFirst({ where: { sysCode } });
  return menu;
}

async function handler(req: NextRequest) {
  // const auth = await authenticateRequest(req);
  // if (!auth.success || !auth.user) {
  //   return errorResponse(auth.error || '未认证', 401);
  // }

  let body: any;
  try {
    body = await req.json();
  } catch {
    return errorResponse('请求体需为 JSON', 400);
  }

  const { content: contentInput, agent: agentInput, categoryName, imageUrl, svgString, sysCode } = body || {};
  if (!contentInput || !contentInput.title) return errorResponse('缺少内容标题', 400);
  if (!categoryName || typeof categoryName !== 'string') return errorResponse('缺少分类名称', 400);
  if (!sysCode || typeof sysCode !== 'string') return errorResponse('缺少 sysCode', 400);

  // 1) 分类：默认挂载到 amazing-website 菜单下
  const menu = await ensureAmazingWebsiteMenu(sysCode);
  if (!menu) {
    return errorResponse('指定的菜单不存在', 404);
  }
  let category = await prisma.category.findFirst({ where: { name: categoryName, menuId: menu.id } });
  if (!category) {
    category = await prisma.category.create({ data: { name: categoryName, menuId: menu.id } });
  }

  // 2) 上传封面：优先 imageUrl，其次 svgString
  let coverRecord: { id: string; url: string; path: string } | null = null;
  try {
    if (imageUrl && typeof imageUrl === 'string' && imageUrl.startsWith('http')) {
      const res = await fetch(imageUrl, { redirect: 'follow' });
      if (!res.ok) {
        throw new Error(`下载图片失败: ${res.status}`);
      }
      const bytes = await res.arrayBuffer();
      const buffer = Buffer.from(bytes);
      const ext = guessExt(res.headers.get('content-type'), imageUrl);
      const safeName = `cover_${randomUUID()}.${ext}`;
      const stored = await uploadFile(buffer, safeName, 'covers/');
      const record = await prisma.file.create({
        data: {
          userId: 'cmgxfef8j0000pfgs6j9a0kff',
          provider: 'minio',
          bucket: process.env.MINIO_BUCKET_NAME || 'kason-world',
          path: stored.path,
          url: stored.url,
          mimeType: stored.mimeType,
          size: stored.size,
          visibility: 'public',
          category: 'image',
          source: 'system-create-content',
          status: 'active',
        }
      });
      coverRecord = { id: record.id, url: record.url, path: record.path };
    } else if (svgString && typeof svgString === 'string' && svgString.trim().length > 0) {
      const buffer = Buffer.from(svgString, 'utf-8');
      const safeName = `cover_${randomUUID()}.svg`;
      const stored = await uploadFile(buffer, safeName, 'covers/');
      const record = await prisma.file.create({
        data: {
          userId: 'cmgxfef8j0000pfgs6j9a0kff',
          provider: 'minio',
          bucket: process.env.MINIO_BUCKET_NAME || 'kason-world',
          path: stored.path,
          url: stored.url,
          mimeType: stored.mimeType || 'image/svg+xml',
          size: stored.size,
          visibility: 'public',
          category: 'svg',
          source: 'system-create-content',
          status: 'active',
        }
      });
      coverRecord = { id: record.id, url: record.url, path: record.path };
    }
  } catch (e: any) {
    // 若 imageUrl 下载失败，尝试使用 svgString 作为兜底
    if (svgString && typeof svgString === 'string' && svgString.trim().length > 0) {
      const buffer = Buffer.from(svgString, 'utf-8');
      const safeName = `cover_${randomUUID()}.svg`;
      const stored = await uploadFile(buffer, safeName, 'covers/');
      const record = await prisma.file.create({
        data: {
          userId: 'cmgxfef8j0000pfgs6j9a0kff',
          provider: 'minio',
          bucket: process.env.MINIO_BUCKET_NAME || 'kason-world',
          path: stored.path,
          url: stored.url,
          mimeType: stored.mimeType || 'image/svg+xml',
          size: stored.size,
          visibility: 'public',
          category: 'svg',
          source: 'system-create-content',
          status: 'active',
        }
      });
      coverRecord = { id: record.id, url: record.url, path: record.path };
    } else {
      console.error('封面上传失败:', e);
    }
  }

  // 3) 智能体：如有 agent 或内容类型为 2，则先创建 Agent
  const DEFAULT_AGENT_KEY = 'fastgpt-tf9MLibjeFKmnQkgbkjNXdf4ttXWWvHruCqRnojPT7vwnyi3xyZkxK8kZQqV';
  let agentId: string | undefined;
  const isAgentContent = !!agentInput || Number(contentInput.type) === 2;
  if (isAgentContent) {
    const name = agentInput?.name || contentInput.title || `智能体_${randomUUID().slice(0,8)}`;
    const secretKey = agentInput?.secretKey || DEFAULT_AGENT_KEY;
      try {
        const created = await prisma.agent.create({
          data: {
            name,
            secretKey,
            welcomeText: agentInput?.welcomeText ?? null,
            prompt: agentInput?.prompt ?? null,
            canUploadImg: agentInput?.canUploadImg ?? 0,
            canUploadDoc: agentInput?.canUploadDoc ?? 0,
            isFormEnabled: agentInput?.isFormEnabled ?? 0,
            formJson: agentInput?.formJson ?? null,
          }
        });
        agentId = created.id;
      } catch (err: any) {
        // 唯一键冲突则加随机后缀重试一次
        const fallbackKey = `${secretKey}-${randomUUID().slice(0,8)}`;
        const created2 = await prisma.agent.create({
          data: {
            name,
            secretKey: fallbackKey,
            welcomeText: agentInput?.welcomeText ?? null,
            prompt: agentInput?.prompt ?? null,
            canUploadImg: agentInput?.canUploadImg ?? 0,
            canUploadDoc: agentInput?.canUploadDoc ?? 0,
            isFormEnabled: agentInput?.isFormEnabled ?? 0,
            formJson: agentInput?.formJson ?? null,
          }
        });
        agentId = created2.id;
      }
  }

  // 4) 创建内容，并关联分类与封面
  const newContent = await prisma.content.create({
    data: {
      title: contentInput.title,
      content: contentInput.content ?? null,
      summary: contentInput.summary ?? null,
      url: contentInput.url ?? null,
      type: Number(contentInput.type ?? (agentId ? 2 : 1)),
      isBanner: Number(contentInput.isBanner ?? 0),
      agentId: agentId ?? null,
      coverId: coverRecord?.id ?? null,
    }
  });

  // 建立分类关联（避免重复）
  const existsRel = await prisma.contentCategory.findFirst({
    where: { contentId: newContent.id, categoryId: category.id },
  });
  if (!existsRel) {
    await prisma.contentCategory.create({ data: { contentId: newContent.id, categoryId: category.id } });
  }

  return successResponse({
    contentId: newContent.id,
    agentId: agentId,
    categoryId: category.id,
    cover: coverRecord ? { fileId: coverRecord.id, url: coverRecord.url, path: coverRecord.path } : null,
  });
}

export const POST = withMiddleware(handler);
export async function OPTIONS() { return optionsResponse(); }